﻿using RMS.Common;
using RMS.EF.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;

namespace RMS.BLL
{
    public class RoleBll
    {

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model">新增的模型实体</param>
        /// <returns></returns>
        public CommonOutPutVm Add(RMS_Role model)
        {
            var result = new CommonOutPutVm();
            #region 输入验证
            var errdic = model.Validate();
            if (errdic != null)
            {
                result.ErrorDic = errdic;
                return result;
            }
            #endregion
            #region 默认值赋值
            var now = DateTime.Now;
            model.Id = Guid.NewGuid().ToString();
            model.EDeleted = E_Deleted.Normal;
            model.CreationTime = now;
            model.CreationUser = model.LastUpdateUser;
            model.LastUpdateTime = now;
            #endregion
            using (var db = new RMSEntities())
            {
                #region 存在验证
                var exist = db.RMS_Role.AsNoTracking().Any(p => p.Deleted == (int)E_Deleted.Normal && p.Id != model.Id && (p.Name == model.Name));
                if (exist)
                {
                    result.Message = "名称已经存在";
                    return result;
                }
                #endregion
                #region 保存
                db.RMS_Role.Add(model);
                int row = db.SaveChanges();
                if (row != 1)
                {
                    result.Message = "新增角色保存异常：" + model.Id;
                    return result;
                }
                #endregion
            }
            result.IsSuccess = true;
            result.Message = "保存成功";
            return result;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model">修改后的模型实体</param>
        /// <returns></returns>
        public CommonOutPutVm Updata(RMS_Role model)
        {
            var result = new CommonOutPutVm();
            #region 输入验证
            var errdic = model.Validate();
            if (errdic != null)
            {
                result.ErrorDic = errdic;
                return result;
            }
            #endregion
            #region 默认值赋值
            model.LastUpdateTime = DateTime.Now;
            #endregion
            using (var db = new RMSEntities())
            {
                #region 存在验证
                var exist = db.RMS_Role.AsNoTracking().Any(p => p.Deleted == (int)E_Deleted.Normal && p.Id != model.Id && (p.Name == model.Name));
                if (exist)
                {
                    result.Message = "名称已经存在";
                    return result;
                }
                #endregion
                #region 保存
                db.Entry(model).State = EntityState.Modified;
                db.Entry(model).Property(p => p.Deleted).IsModified = false;
                db.Entry(model).Property(p => p.CreationTime).IsModified = false;
                db.Entry(model).Property(p => p.CreationUser).IsModified = false;
                int row = db.SaveChanges();
                if (row != 1)
                {
                    result.Message = "修改角色保存异常：" + model.Id;
                    return result;
                }
                #endregion
            }
            result.IsSuccess = true;
            result.Message = "保存成功";
            return result;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page">分页参数</param>
        /// <returns></returns>
        public CommonOutPutVm GetByPage(PageParamsT<S_RMS_Role> page)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_Role.Where(p => p.Deleted == (int)E_Deleted.Normal);
                #region where
                if (!string.IsNullOrWhiteSpace(page.SearchModel.SearchValue))
                {
                    q = q.Where(p => p.Name.Contains(page.SearchModel.SearchValue));
                }
                if (page.SearchModel.Status != E_Status.All)
                {
                    q = q.Where(p => p.Status == (int)page.SearchModel.Status);
                }
                #endregion
                page.Total = q.Count();
                #region order by
                if (string.IsNullOrWhiteSpace(page.Order))
                {
                    q = q.OrderBy(p => p.Ordering);
                }
                else
                {
                    var orderExpression = string.Format("{0} {1}", page.Order, page.OrderType);
                    q = q.OrderBy(orderExpression);
                }
                #endregion
                q = q.Skip(page.Start).Take(page.Length);
                result.Data = q.ToList();
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id">数据Id字符串","分隔</param>
        /// <returns></returns>
        public CommonOutPutVm Delete(string id)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            #region 验证
            if (string.IsNullOrWhiteSpace(id))
            {
                result.Message = "请选择一条数据";
                return result;
            }
            #endregion
            #region 删除
            using (var db = new RMSEntities())
            {
                db.Database.ExecuteSqlCommand("update RMS_Role set Deleted=1 where Id in ('" + id + "')");
                db.SaveChanges();
            } 
            #endregion
            result.IsSuccess = true;
            result.Message = "删除成功";
            return result;
        }
        /// <summary>
        /// 根据Id获取未删除的实体
        /// </summary>
        /// <param name="id">Id主键</param>
        /// <returns></returns>
        public CommonOutPutVm GetById(string id)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var data = db.RMS_Role.AsNoTracking().FirstOrDefault(p => p.Id == id && p.Deleted == (int)E_Deleted.Normal);
                if (data == null)
                {
                    result.Message = "角色不存在";
                    return result;
                }
                result.Data = data;// EntityHelper.ConverToTEntity<RMS_Role_Extend>(data);
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 关联菜单
        /// </summary>
        /// <param name="id">角色Id</param>
        /// <param name="menuId">菜单Id集合</param>
        /// <param name="programId">项目Id</param>
        /// <param name="userId">操作用户Id</param>
        /// <returns></returns>
        public CommonOutPutVm Relation_Menu(string id, List<string> menuId, string programId, string userId)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        DateTime now = DateTime.Now;
                        #region 根据角色Id删除所有关联
                        string sql = @"update rm set rm.Deleted=1, rm.LastUpdateTime=@now, rm.LastUpdateUser=@userId
from RMS_Role_Menu rm left join RMS_Menu m on rm.MenuId=m.Id
where rm.RoleId=@id and m.ProgramId=@programId";
                        db.Database.ExecuteSqlCommand(sql,
                            new SqlParameter("@id", id),
                            new SqlParameter("@now", now),
                            new SqlParameter("@userId", userId),
                            new SqlParameter("@programId", programId));
                        db.SaveChanges();
                        #endregion
                        #region 修改已有关联状态为启用
                        string menuIdstr = string.Join("','", menuId);
                        sql = @"update RMS_Role_Menu set Deleted=0, LastUpdateTime=@now, LastUpdateUser=@userId where RoleId=@id and MenuId in ('" + menuIdstr + "')";
                        db.Database.ExecuteSqlCommand(sql,
                            new SqlParameter("@id", id),
                            new SqlParameter("@now", now),
                            new SqlParameter("@userId", userId)); 
                        #endregion
                        #region 不存在关联的需要添加
                        var existMenuId = db.RMS_Role_Menu.AsNoTracking().Where(p => p.RoleId == id && menuId.Contains(p.MenuId)).Select(p => p.MenuId);
                        if (existMenuId.Count() > 0)
                        {
                            var models = menuId.Where(p => !existMenuId.Contains(p)).Select(p => new RMS_Role_Menu()
                            {
                                Id = Guid.NewGuid().ToString(),
                                RoleId = id,
                                MenuId = p,
                                Deleted = (int)E_Deleted.Normal,
                                CreationTime = now,
                                CreationUser = userId,
                                LastUpdateTime = now,
                                LastUpdateUser = userId
                            });
                            db.RMS_Role_Menu.AddRange(models);
                            db.SaveChanges();
                        }
                        #endregion
                        tran.Commit();
                        result.IsSuccess = true;
                        result.Message = "操作成功";
                    }
                    catch (Exception e)
                    {
                        tran.Rollback();
                        throw e;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 根据角色和项目获取菜单关联信息
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <param name="programId">项目Id</param>
        /// <returns></returns>
        public CommonOutPutVm Get_RoleMenu_ByRoleIdAndProjectId(string roleId, string programId)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {

                var q = db.RMS_Role_Menu.Join(db.RMS_Menu, a => a.MenuId, b => b.Id, (a, b) =>
                    new {
                        Role_Menu=a,
                        ProgramId=b.ProgramId,
                        Ordering = b.Ordering
                    })
                    .Where(p => p.Role_Menu.Deleted == (int)E_Deleted.Normal && p.Role_Menu.RoleId == roleId && p.ProgramId == programId)
                    .OrderBy(p=>p.Ordering)
                    .Select(p=>p.Role_Menu);
                var data = q.ToList();
                if (data == null)
                {
                    data = new List<RMS_Role_Menu>();
                }
                result.Data = data;
            }
            result.IsSuccess = true;
            return result;
        }

        /// <summary>
        /// 获取所有可用角色
        /// </summary>
        /// <returns></returns>
        public CommonOutPutVm GetAllEnable()
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_Role.Where(p => p.Deleted == (int)E_Deleted.Normal && p.Status == (int)E_Status.Enable).OrderBy(p => p.Ordering);
                result.Data = q.ToList();
            }
            result.IsSuccess = true;
            return result;
        }
    }
}
